package br.com.rotary.utilitario;

import br.com.rotary.modelo.Anexo;
import br.com.rotary.servico.AnexoServico;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.model.CroppedImage;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class viewImage implements Serializable {

    @EJB
    AnexoServico annexService;
    private String url;
    private boolean cortando;
    private CroppedImage croppedImage;
    private Anexo image;

    @PostConstruct
    public void init() throws IOException {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        url = params.get("annex");
        croppedImage = new CroppedImage();
        try {
            image = annexService.pesquisar(Long.parseLong(url));
            url = image.getId() + "";
        } catch (Exception e) {
            System.err.println(e);
        }

    }

    public static StreamedContent convertImage(String caminhoImagem) {

        StreamedContent imagem = null;

        File f = new File(caminhoImagem);
        if (f.exists()) {
            InputStream stream;
            try {
                stream = new FileInputStream(f);
                imagem = new DefaultStreamedContent(stream, "image/jpeg");
            } catch (Exception e) {
                System.err.println(e);
            }
        }

        return imagem;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void rotateImageDireta() {
        try {
            rotateImage(90);
        } catch (IOException ex) {
            Logger.getLogger(viewImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void rotateImageEsquerda() {
        try {
            rotateImage(-90);
        } catch (IOException ex) {
            Logger.getLogger(viewImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void rotateImage(int ang) throws IOException {
        String path = image.getUrl().concat(image.getNome());

        InputStream bais = new ByteArrayInputStream(Files.readAllBytes(Paths.get(path)));

        BufferedImage original;
        try {
            original = ImageIO.read(bais);

            BufferedImage dest = new BufferedImage(original.getHeight(), original.getWidth(), original.getType());
            Graphics2D surface = dest.createGraphics();
            AffineTransform rotation = new AffineTransform();
            rotation.setToTranslation((dest.getWidth() - original.getWidth()) / 2.0, (dest.getHeight() - original.getHeight()) / 2.0);
            rotation.rotate(Math.toRadians(ang), original.getWidth() / 2.0, original.getHeight() / 2.0);
            surface.transform(rotation);
            surface.drawImage(original, 0, 0, null);
            surface.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(dest, "jpg", baos);

//            image.setArquivo(baos.toByteArray());
//            annexService.update(image);

            FileOutputStream fos = new FileOutputStream(path);
            fos.write(baos.toByteArray());
            fos.close();

//            FacesContext.getCurrentInstance().getExternalContext().redirect("viewImage.xhtml?annex=" + image.getId());

        } catch (IOException ex) {
            Logger.getLogger(viewImage.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public CroppedImage getCroppedImage() {
        return croppedImage;
    }

    public void setCroppedImage(CroppedImage croppedImage) {
        this.croppedImage = croppedImage;
    }

    public void ativaCrop() {
        if (!cortando) {
            cortando = true;
        } else {
            cortando = false;
        }
    }

    public Anexo getImage() {
        return image;
    }

    public void setImage(Anexo image) {
        this.image = image;
    }

    public boolean isCortando() {
        return cortando;
    }

    public void setCortando(boolean cortando) {
        this.cortando = cortando;
    }

    public String getRequestURL() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        String requestURL = request.getRequestURL().toString();
        String urlRequest = requestURL.substring(0, requestURL.lastIndexOf("/"));
        return urlRequest;
    }
}
